<?php
	defined('_JEXEC') or die('Restricted access');
	require_once(CUTEENGINE_BASE_ACTION_PATH."base_action_class.php");
    require_once(CUTEENGINE_BASE_STEP_PATH."base_step_class.php");
	require_once(CUTEENGINE_ACTIONS_PATH. 'action_manage_twitter' . DIRECTORY_SEPARATOR.'tmhoauth'. DIRECTORY_SEPARATOR.'tmhOAuth.php');
	//
    // t_action_manage_twitter
    //
	class t_action_manage_twitter extends t_base_action
	{
        // property declaration
		// protected        

		
		// property declaration
		// public
		// L
		const language_position_per_sent = 1;
		const language_position_per_not_sent = 2;
		const language_position_per_empty_to_field = 3;
		const language_position_per_empty_from_field = 4;
		const language_position_per_empty_subject_field = 5;
		const language_position_per_empty_message_field	= 6;	
		const language_position_last = 7;		
		// P
        const proper_properties_position_per_query = 0;
        const proper_properties_position_per_parameters_names = 1;
		const proper_properties_position_per_message = 2;
        const proper_properties_position_last = 3;		
        // R
        const required_fields_count = 2;
      
        // method declaration
    	// protected
        // G
		static function get_help_proper_property($a_index)
		{
			$local_return = 'NO HELP AVAILABLE';
			/*switch ($a_index) 
            {
                case self::proper_properties_position_:
					$local_return = '';
				break;                
			}*/
			return $local_return;
		}
        static function get_default_proper_property($a_index)
		{
			$local_return = '';
			//echo "a_index: $a_index<br>";
			/*switch ($a_index) 
            {
				case self::proper_properties_position_per_:
					$local_return = '';
				break;				
			}*/
			return $local_return;
		}		
        protected function get_proper_properties_position_last()
        {
            return self::proper_properties_position_last;
        }
		protected function get_required_fields_count()
        {
            return self::required_fields_count;
        }
        

		// I
        protected function initialize_action()
        {		

			if (! $this->initialized)
			{
                parent::initialize_action();
				
				
                //$this->initialized = true;

			}
			return $this->initialized;
		}		
        protected function initialize_step_execution()
        {		
			$local_step = $this->steps_list[$this->current_step_index];
			$local_index = $this->current_step_index;
			$local_step->initialize();
			$local_class = get_class($local_step);
			
			if ($local_index == t_base_action::step_criteria)
			{
				$this->custom_execute_step($local_step);                        
				
				
			}		
			else
			{
				$this->execute_step($local_step);                                            
			}

		}	
        protected function custom_execute_step($a_step)        
        {
			//echo "this->current_step_index: $this->current_step_index<br>";
            $local_next_step = $this->steps_list[$this->current_step_index + 1];
			$local_field = $a_step->field;
			//echo "local_field->name: ".$local_field->name."<br>"; 
			if ($local_field)
			{
				$local_start_tag = $local_field->get_start_tag();
				$local_field_class = get_class($local_field);    
			}			
		    $local_class = get_class($a_step);
           
            
            switch ($local_class) 
            {
				/*********** t_step_ajax_get ***********/
				case t_step_ajax_get:
					$a_step->code = "
	var local_parent = ".t_cuteengine::javascript_instance_name."['".$local_start_tag->name."'];
    var local_argoument = local_parent.prepare_childs_values_to_send('".$local_start_tag->name."');
    if (!local_argoument)
        return false;
    ". $this->get_content_loader_code($local_next_step->code,true,true);
					
                break;                
               
            }
        }
		
        // method declaration
    	// public
        public function __construct($a_parent_component,$a_parent_part,$a_common_properties_str, $a_proper_properties_str) 
		{
            parent::__construct($a_parent_component,$a_parent_part,$a_common_properties_str, $a_proper_properties_str);
            //echo "count:".count($this->fields_list);
			// steps
			if ($this->is_executable())
			{
				$this->steps_list[t_base_action::step_start] = t_base_step::create_step_from_string('|t_step_ajax_start|'.$this->get_action_name().'_start|'.
					$this->fields_list[t_base_action::step_start].'|'); 
				$this->steps_list[t_base_action::step_criteria] = t_base_step::create_step_from_string('|t_step_ajax_get|'.$this->get_action_name().'_criteria|'.
					$this->fields_list[t_base_action::step_criteria].'|');     
			}
			
			
		}
        // D
		public function do_action_from_ajax($a_json_result,$a_connection = null)
        {
			//echo __METHOD__ . "<br>"; 
			global $g_ambient_namespace;
			if ($a_connection == null)
				$local_connection = $g_ambient_namespace->connection;
			else
				$local_connection = $a_connection;
			if ($a_json_result == null)
				$local_result = new t_content_loader_result;
			else
				$local_result = $a_json_result;
			//
            $local_component = $this->parent_component;
			$local_parameter = parent::do_action_from_ajax();
			
			//GETS PARAMETERS 
			$local_actions_array = $this->is_there_child_action_class(array('t_action_get_parameters')); 
			foreach ($local_actions_array as $local_action) 
			{
				
				if (isset($local_action->parameter))
				{
					//echo "ciao1<br>";
					//print_r($local_action->parameter);
					//echo "local_action->parameter->argument: ".$local_action->parameter->argument."<br>";
					$local_value_array = explode(t_url_parameter::separator_level_0,$local_action->parameter->argument);
					foreach ($local_value_array as $local_index => $local_value) 
					{
						//echo "local_value:$local_value<br>";
						$local_parameter->append_to_argument_value(3,$g_ambient_namespace->hide_separator($local_value));
					}
					
				}	
			}
			//print_r($local_parameter);
			// QUERY
			$local_query_name = $this->get_action_name()."_query";
            $local_query_query = trim($this->proper_properties_array[self::proper_properties_position_per_query]);
            $local_component->new_query(
				$local_query_name,
				$local_query_query,
				$local_connection);
            //$local_parameters_names = explode(t_strings_utility_namespace::separator_level_2,
                //substr($this->proper_properties_array[self::proper_properties_position_per_parameters_names],1,-1));    
            $local_parameters_names = $this->proper_properties_array[self::proper_properties_position_per_parameters_names];
			
			//
			$local_query_query = $local_component->get_query(
				$local_query_name);
			$local_query_query->reset_parameters();
			//echo "ARGOMENTO ID: ". $local_parameter->get_argument_value(2);    
			echo "PARAMETER: ". $g_ambient_namespace->remove_hide_separator($local_parameter->get_argument_value(3));  
			$local_parameters_array = $g_ambient_namespace->remove_hide_separator(explode(t_url_parameter::separator_level_1,$local_parameter->get_argument_value(3)));
			
			foreach ($local_parameters_names as $local_parameter_name_index=>$local_parameter_name) 
			{
				$local_db_field_index = $local_query_query->get_parameter_index_by_name($local_parameter_name);
				if ($local_db_field_index >= -1)
				{
					echo "index: $local_db_field_index - value:".$local_parameters_array[$local_parameter_name_index];
					$local_query_query->set_value_parameter(
						$local_parameters_array[$local_parameter_name_index],$local_db_field_index);
					
					if ($local_query_query->is_not_correct_value($local_db_field,$local_parameters_array[$local_parameter_name_index],$local_db_field_index))
						if($local_invalid_value_list == '')
							$local_invalid_value_list = "Fields values ivalid for: `$local_db_field->name`";
						else
							$local_invalid_value_list .= ", `$local_db_field->name`";
				}			
			}	
			if ($local_invalid_value_list != '')
			{
				$a_json_result->error_msg  = $local_invalid_value_list;
			}	
			else
			{
				$local_message = $this->proper_properties_array[self::proper_properties_position_per_message];	
				if ($local_message == "")
				{
					$local_error_msg = $this->lang[self::language_position_per_empty_message_field];
				} 
				else 
					$local_is_to_send = true;
				//echo "local_is_to_send: $local_is_to_send<br>";
				// SEND MAIL
				if ($local_is_to_send)
				{
					$local_error_msg = $local_query_query->execute_function_from_query_result($this,"post_tweet",
						array($local_message,$local_result));
					if ($local_result->succeeded === true)
					{
						$this->execute_child_ations($local_result,$local_query_query->connection,$local_query_query);
					}
					//echo "local_error_msg: $local_error_msg<br>"; 
				}	
				else
				{
					$local_result->succeeded = false;
					
				}	
				$local_field = $this->steps_list[t_base_action::step_start]->field;
				//echo "get_class(local_field): ". get_class($local_field) ."<br>";
				if ((get_class($local_field)) == 't_field_processes_engine')
				{
					if ($local_result->succeeded === false)
					{
						$local_field->apply_error_result_script($local_result);
						
					}	
					else
					{
						$local_field->apply_result_script($local_result);
					}
					echo $local_result->get_json_string();					
				}
				else
				{
					if ($this->enable_language)
						$local_result->error_msg = $local_error_msg;
					if ($a_json_result == null)
						echo $local_result->get_json_string();
				}		
				
			}
        }
		
		public function get_language_position_last()
        {
            return self::language_position_last;
        }
		// I
		public function is_executable()
		{
			return ((($this->fields_list[t_base_action::step_start] != '') && ($this->fields_list[t_base_action::step_criteria] != '')) ||
				($this->force_executable == true));
		}
        // S
		public function post_tweet($a_query_parameter,$a_current_row_no,$a_rows_count,$a_tweet_parameter)
		{
			//echo "post_tweet<br>";
			$local_tweet_text =  $a_query_parameter->set_field_value_to_text($a_tweet_parameter[0]);
			$local_image = '';
			
			
			$connection = new tmhOAuth(array(
				'consumer_key' => 'eE22fKZqmQ4YMxzol5rfQ',
				'consumer_secret' => 'zOwcCtZuX1xtVxQzzBNLzQwCpUfiiFsLwbt5qOEQ24',
				'user_token' => '281037787-G8pcsRKA3fAVdrF9oH7xdQmxD0Q6rzO5r0P4CuLz',
				'user_secret' => 'kaRiotTAmaAL6UnFeBc3BrQjzVB7hA6VzxYli5BCWY4',
			));
			
			
			if($local_image != ''){
				$connection->request('POST', 
				'https://upload.twitter.com/1.1/statuses/update_with_media.json', 
				array('media[]'  => "@{$local_image}",'status'   => $local_tweet_text),
				true,
				true
				);
				//return '{ "code" : "'.$connection->response['code'].'" , "response" : '.$connection->response['response'].' }';
			} else {
				$connection->request('POST', 
				$connection->url('1.1/statuses/update'), 
				array('status' => $local_tweet_text));
				//$string = '';
				//foreach($this->response as $key => $val){
				//	$string .= $key.' - ';
				//}
				//return $string;	  
				//return '{ "code" : "'.$connection->response['code'].'" , "response" : '.$connection->response['response'].' }';
			}
			echo "POST RESULT ".$connection->response['response']."<BR>";
			
/*
			if ($local_result == true)
			{*/
				$a_tweet_parameter[1]->succeeded = true;
				$local_error_msg = $this->lang[self::language_position_per_sent];
			/*}	
			else
			{
				$a_tweet_parameter[4]->succeeded = false;
				$local_error_msg = $this->lang[self::language_position_per_not_sent];
			}*/
			$a_query_parameter->function_result = $connection->response['response'];
		}
    }
?>    